package springboot_rabbitmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springboot_rabbitmq.callback.MyCallback;


import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @author 帅小伙
 * @date 2022/1/6
 * @description
 */

@RestController
@RequestMapping("/confirm")
@Slf4j
public class Producer {


    public static final String CONFIRM_EXCHANGE_NAME = "confirm.exchange";
    public static final String CONFIRM_QUEUE_NAME = "confirm.queue";
    public static final String CONFIRM_EXCHANGE_QUEUE_KEY = "confirm.key";

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MyCallback myCallback;

    // 当RabbitTemplate 注入进来之后 首先执行的方法
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(myCallback);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnCallback(myCallback);
    }


    @GetMapping("sendMsg/{message}")
    public void sendMsg(@PathVariable String message) {
        // 相关数据
        CorrelationData correlationData = new CorrelationData("1");
        /*
         * 发送给那个交换机
         * 发送路由key
         * 发送信息
         * */
        rabbitTemplate.convertAndSend(CONFIRM_EXCHANGE_NAME, CONFIRM_EXCHANGE_QUEUE_KEY, "消息来自confirm为队列" + message,correlationData);
        // 直接用日志
        log.info("当前时间:{}发送一条消息{}给队列", new Date(), message);


        CorrelationData correlationData2 = new CorrelationData("2");
        rabbitTemplate.convertAndSend(CONFIRM_EXCHANGE_NAME, CONFIRM_EXCHANGE_QUEUE_KEY+"ss" ,"消息来自confirm为队列" + message,correlationData2);
        // 直接用日志
        log.info("当前时间:{}发送一条消息{}给队列", new Date(), message);

    }
}
